import * as path from 'path';
import { defineConfig, Plugin } from 'vite';
import vue from '@vitejs/plugin-vue';
import legacy from '@vitejs/plugin-legacy';
import { setNodeEnv } from "./src/utils/env";
import { vitePluginStore } from "./src/utils/store";
import { vitePluginLocales } from "./src/utils/i18n";
import { vitePluginMock } from "./src/utils/mock";
import { vitePluginIconSvg } from "./src/components/IconSvg/plugin";

// https://vitejs.dev/config/
export default defineConfig(({ mode, command })=> {

  // 自定义设置 nodejs .env
  setNodeEnv(mode);

  // 开发服务器端口
  const port: number =  parseInt(process.env.APP_PORT || '3000');

  // 插件
  const plugins: (Plugin | Plugin[])[] = [
    vue(),
    vitePluginStore(),
    vitePluginLocales(),
    vitePluginIconSvg(),
  ]

  // vitePluginMock
  mode === 'development' && process.env.APP_MOCK === 'true' && plugins.push(vitePluginMock());
  // @vitejs/plugin-legacy
  command === 'build' && plugins.push(legacy());
  
  let serverConfig={
	  open:true
  }
  if(!process.env.APP_MOCK){
	 serverConfig={
     // 如果使用docker-compose开发模式，设置为false
          open: true,
          port:process.env.VUE_APP_PORT,
          proxy: {
            // 把key的路径代理到target位置
            // detail: https://cli.vuejs.org/config/#devserver-proxy
            [process.env.VITE_BASE_PATH]: { // 需要代理的路径   例如 '/api'
              target: `${process.env.VUE_APP_APIHOST}/`, // 代理到 目标路径
              changeOrigin: true,
              // rewrite: path => path.replace(new RegExp('^' + env.VITE_BASE_API), ''),
            }
          },
   }
  }
  return {
    base: '/',
    plugins,
    resolve: {
      alias: {
        '@': path.resolve(__dirname, './src'),
      },
    },
	
   server: serverConfig
   
  }
})
